import { TypeAdapterFactory } from '../factory/TypeAdapterFactroy'
import { ReaderIn } from '../ReaderIn'
import { FIRST_READ } from '../TypeConstants'
import { WriterOut } from '../WriterOut'

export class DlJsonUtils {
  /**
   * @param json json对象
   * @param target 数据源默认对象
   * @returns
   */
  static fromJsonObj<T>(json: Object, target: T): T {
    let factory = new TypeAdapterFactory()
    let type = factory.create(target)
    return type.read(new ReaderIn(
      json, target, factory,FIRST_READ
    )).value()
  }

  /**
   * @param jsonStr jsonString
   * @param target 数据源对象
   * @returns
   */
  static fromJsonString<T>(jsonStr: string, target: T): T {
    return this.fromJsonObj(JSON.parse(jsonStr), target)
  }

  /**
   *
   * @param obj 对象转json
   * @returns
   */
  static fromObjToString(obj: ESObject): string {
    let factory = new TypeAdapterFactory()
    let type = factory.create(obj)
    let out = new WriterOut(obj, factory)
    return JSON.stringify(type.write(out).value())
  }

  /**
   * 针对数组序列源方法,只用于反序列化的数组json
   * @param target 源数组
   * @param t 数组内默认对象
   * @returns
   */
  static defaultReaderTargetArray<T>(target: Array<T>, t: T): Array<T> {
    target.push(t)
    return target
  }
}